package util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.media.MediaMetadataRetriever;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

public class MusicUtil {
    public final static String PATH = "/sdcard/Music"; // /sdcard/Music
    /*
       获取音乐列表
     */
    public static List<String> readDirectory(){
        List<String> musiclist = new ArrayList<>();
        File directory = new File(PATH);
        //Log.e("TAG", "readDirectory: " + directory.length());
        File[] files = directory.listFiles();
        for (File file : files) {
            //Log.e("TAG", "readDirectory: "+ file.getPath() );
            musiclist.add(file.getPath());
        }
        return musiclist;
    }
    public static String getTitle(String filePath) throws Exception {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();

            try {
                // 设置数据源为指定的文件路径
                retriever.setDataSource(filePath);
                // 获取标题
                String title = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);

                //titlelists.add(title);
                return title;

            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                // 确保释放资源
                retriever.release();
            }
        }
    @Nullable
    public static String getArt(String filePath) throws Exception {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            // 设置数据源为指定的文件路径
            retriever.setDataSource(filePath);
            // 获取艺术家
            String artist = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
            //artlists.add(artist);
            return artist;
        } catch (Exception e) {
            //Log.e("TAG", "getArt: "+ filePath + "read error");
            e.printStackTrace();
            return null;
        } finally {
            // 确保释放资源
            retriever.release();
        }
    }
        public static Bitmap getBitmap(String file){
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();

            retriever.setDataSource(file);
            byte[] albumArt = retriever.getEmbeddedPicture();
            Bitmap bitmap = BitmapFactory.decodeByteArray(albumArt,0,albumArt.length);
            return bitmap;
        }
}
